package mq.simple;

import com.rabbitmq.client.*;
import mq.Constants.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author: Themberfue
 * @date: 2025/4/26 20:11
 * @description:
 */
public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // TODO 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST); // ? 公网 IP
        connectionFactory.setPort(Constants.PORT); // ? 端口
        connectionFactory.setUsername(Constants.USER_NAME); // ? 用户名
        connectionFactory.setPassword(Constants.PASSWORD); // ? 密码
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); // ? 虚拟主机
        Connection connection = connectionFactory.newConnection();

        // TODO 2. 开启信道
        Channel channel = connection.createChannel();

        // TODO 3. 声明队列，可以省略（如果生产者未声明队列的话，消费者也未声明队列则会报错，因为不知道和哪个队列绑定了）
        channel.queueDeclare("hello", true, false, false, null);

        // TODO 4. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /**
             * 从队列中，收到消息就会执行该方法
             * @param consumerTag the <i>consumer tag</i> associated with the consumer
             * @param envelope packaging data for the message 封包的消息，比如交换机，队列名称等...
             * @param properties content header data for the message
             * @param body the message body (opaque, client-specific byte array)
             * @throws IOException IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息：" + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);

        Thread.sleep(1000);

        // TODO 5. 释放资源
        channel.close(); // ! 先关闭 channel
        connection.close();
    }
}
